<?php
/**
 * This controller is responsible for processing all action of FrontAdminMenu
 *
 */
class Backend_AjaxController extends RCMS_Core_BaseController {

	protected $_websiteUrl;

	protected $_smtpHost;

	protected $_smtpLogin;

	protected $_smtpPassword;

	protected $_adminEmail;

	protected $_smtpConfigArray;

	protected $_configTableArray;

	protected $_domain;

	protected $_pageUrl;

	protected $_seoParser = null;


	/**
	 * This method loads each time when we call the class method.
	 * @return void
	 */
	public function init() {
		$this->_model = new Backend_AjaxModel();
		parent::init();
		$this->_websiteUrl = $this->_config->website->website->url;
		$this->_seoParser = new RCMS_Object_Parser_SeoParser();
	}

	/**
	 * This is function inits smtp settings
	 * @return void
	 */
	private function _initSmtp() {
		$this->_domain = ($this->_smtpHost)? ucfirst($this->_smtpHost) : $this->_websiteUrl;
		$configArray = $this->_model->selectAllConfigSettings();
		if($configArray) {
			$this->_configTableArray = $configArray;
			if(isset($configArray['smtp_host']) && $configArray['smtp_host'] != '') {
				$this->_smtpHost = $configArray['smtp_host'];
			}
			if(isset($configArray['smtp_login']) && $configArray['smtp_login'] != '') {
				$this->_smtpLogin = $configArray['smtp_login'];
			}
			if(isset($configArray['smtp_password']) && $configArray['smtp_password'] != '') {
				$this->_smtpPassword = $configArray['smtp_password'];
			}
			if(isset($configArray['admin_email']) && $configArray['admin_email'] != '') {
				$this->_adminEmail = $configArray['admin_email'];
			}
			$this->_smtpConfigArray = array(
				'auth'      => 'login',
				'username'  => $this->_smtpLogin,
				'password'  => $this->_smtpPassword,
				'host'      => $this->_smtpHost
			);
		}
	}

	/**
	 * This is function loads images for edit content.
	 * @return void
	 */
	function loadimagesforeditcontentAction() {
		$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('folder') !== '') {
			$folder = trim($this->getRequest()->getParam('folder'));
			$textareaId = $this->getRequest()->getParam('textarea');
            $path = $this->view->websiteUrl . 'images/' . $folder . '/';
			$strImagesSmall = '';
			$strImagesMedium = '';
			$strImagesLarge = '';
			$strImagesOriginal = '';
			//$strVideo = '';
            $configForImage = $this->_model->selectConfigForImage();

			//got array images
			$imagesSmall = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/small/');
			$imagesMedium = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/medium/');
			$imagesLarge = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/large/');
			//$videoFiles = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/video/');
			$imagesOriginal = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/original/');

			//load small images width=".$configForImage['img_small']['value']."
			if(!empty($imagesSmall)) {
				foreach ($imagesSmall as $imageSmall) {
                    $sizeImage = getimagesize($this->_config->website->website->path.$this->_config->website->website->images.$folder.'/small/'.$imageSmall);
					$elmSmallImage = '<a href=' . $path . 'original/' . $imageSmall . ' title=' . str_replace('-','&nbsp;', ToolsHelper::cropType($imageSmall)).' class=thickbox><img border=0 alt='.str_replace('-','&nbsp;', ToolsHelper::cropType($imageSmall)).' src=' . $path . 'small/' . $imageSmall . ' width='.$sizeImage[0].' height='.$sizeImage[1].' /></a>';
					$strImagesSmall .= '<a href="javascript:;" onmousedown="$(\'#' . $textareaId . '\').tinymce().execCommand(\'mceInsertContent\',false, \'' . $elmSmallImage . '\');">';
					$strImagesSmall .= '<img title="'.$imageSmall.'" style="vertical-align:top; margin: 0px 0px 4px 4px;" border="0" width="65" src="'.$path.'small/'.$imageSmall.'" /></a>';
				}
			}

			$this->view->strImagesSmall = $strImagesSmall . '<div style="clear:both;height:0px;">&nbsp;</div>';
			$this->_websiteUrl = $this->_config->website->website->url;

			//load medium images
			if(!empty($imagesMedium)) {
				foreach ($imagesMedium as $imageMedium) {
                    $sizeImage = getimagesize($this->_config->website->website->path.$this->_config->website->website->images.$folder.'/medium/'.$imageMedium);
					$elmMediumImage = '<a href=' . $path . 'original/' . $imageMedium . ' title=' . str_replace('-','&nbsp;', ToolsHelper::cropType($imageMedium)).' class=thickbox><img border=0 alt='.str_replace('-','&nbsp;', ToolsHelper::cropType($imageMedium)).' src=' . $path . 'medium/' . $imageMedium . ' width='.$sizeImage[0].' height='.$sizeImage[1].' /></a>';
					$strImagesMedium .= '<a href="javascript:;" onmousedown="$(\'#' . $textareaId . '\').tinymce().execCommand(\'mceInsertContent\',false, \'' . $elmMediumImage . '\');">';
					$strImagesMedium .= '<img title="'.$imageMedium.'" style="vertical-align:top; margin: 0px 0px 4px 4px;" border="0" width="65" src="'.$path.'small/'.$imageMedium.'" /></a>';
				}
			}

			$this->view->strImagesMedium = $strImagesMedium . '<div style="clear:both;height:0px;">&nbsp;</div>';

			//load large images
			if(!empty($imagesLarge)) {
				foreach ($imagesLarge as $imageLarge) {
                    $sizeImage = getimagesize($this->_config->website->website->path.$this->_config->website->website->images.$folder.'/large/'.$imageLarge);
					$elmLargeImage = '<a href=' . $path . 'original/' . $imageLarge . ' title=' . str_replace('-','&nbsp;', ToolsHelper::cropType($imageLarge)).' class=thickbox><img border=0 alt='.str_replace('-','&nbsp;', ToolsHelper::cropType($imageLarge)).' src=' . $path . 'large/' . $imageLarge . ' width='.$sizeImage[0].' height='.$sizeImage[1].' /></a>';
					$strImagesLarge .= '<a href="javascript:;" onmousedown="$(\'#' . $textareaId . '\').tinymce().execCommand(\'mceInsertContent\',false, \'' . $elmLargeImage . '\');">';
					$strImagesLarge .= '<img title="'.$imageLarge.'" style="vertical-align:top; margin: 0px 0px 4px 4px;" border="0" width="65" src="'.$path.'small/'.$imageLarge.'" /></a>';
				}
			}

			$this->view->strImagesLarge = $strImagesLarge . '<div style="clear:both;height:0px;">&nbsp;</div>';

			//load original images
			if(!empty($imagesOriginal)) {
				foreach ($imagesOriginal as $imageOriginal) {
                    $sizeImage = getimagesize($this->_config->website->website->path.$this->_config->website->website->images.$folder.'/original/'.$imageOriginal);
					$elmOriginalImage = '<a href=' . $path . 'original/' . $imageOriginal . ' title=' . str_replace('-','&nbsp;', ToolsHelper::cropType($imageOriginal)).' class=thickbox><img border=0 alt='.str_replace('-','&nbsp;', ToolsHelper::cropType($imageOriginal)).' src=' . $path . 'original/' . $imageOriginal . ' width='.$sizeImage[0].' height='.$sizeImage[1].' /></a>';
					$strImagesOriginal .= '<a href="javascript:;" onmousedown="$(\'#' . $textareaId . '\').tinymce().execCommand(\'mceInsertContent\',false, \'' . $elmOriginalImage . '\');">';
					$strImagesOriginal .= '<img title="'.$imageOriginal.'" style="vertical-align:top; margin: 0px 0px 4px 4px;" border="0" width="65" src="'.$path.'small/'.$imageOriginal.'" /></a>';
				}
			}

			$this->view->strImagesOriginal = $strImagesOriginal . '<div style="clear:both;height:0px;">&nbsp;</div>';
		}
		echo json_encode(array('small' => $this->view->strImagesSmall, 'medium' => $this->view->strImagesMedium, 'large' => $this->view->strImagesLarge, 'original' => $this->view->strImagesOriginal));
	}

	/**
	 * This function loads images for removethings.
	 * @return void
	 */
	public function loadimagesforremovethingsAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$folder = trim($this->getRequest()->getParam('folder'));
			if($folder !== '' && is_dir($this->_config->website->website->path . $this->_config->website->website->images . $folder) ) {
				$path = $this->view->websiteUrl . 'images/' . $folder . '/small/';
				$response = '';
				$images = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/small/');

				if(!empty($images)) {
					foreach($images as $image) {
						$response .= "<div align=\"center\" id=\"removethings_one_image\">\n";
						$response .= "<img alt=\"" . ToolsHelper::cropType($image) . "\" title=\"" . $image . "\" border=\"0\" width=\"65\" src=\"" . $path . $image . "\">\n";
						$response .= "<input type=\"checkbox\" name=\"images[" . $image ."]\">\n";
						$response .= "</div>\n";
					}
				}
				$videoPath = $this->_config->website->website->path . $this->_config->website->website->images . $folder . '/video/' ;
				$videoFiles = RCMS_Tools_FilesystemTools::scanDir($videoPath);

				if(!empty($videoFiles)) {
					$response .= "<div style=\"clear:both;margin:5px auto 5px auto;text-align:center;background-color:#eee;\">Videos</div>\n";
					foreach ($videoFiles as $videoFile) {
						$response .= "<div align=\"center\" style=\"height:100px;\" id=\"removethings_one_image\">\n";
						$response .= "<img alt=\"" . ToolsHelper::cropType($videoFile) . "\" title=\"" . $videoFile . "\" border=\"0\" width=\"65\" src=\"" . $this->_config->website->website->url . "system/images/ico_video.gif\">\n";
						$response .= "<span style=\"font-size:9px;font-weight: normal;\">".$videoFile."</span><input type=\"checkbox\" name=\"videos[" . $videoFile ."]\" />\n";
						$response .= "</div>\n" ;
					}
				}
				echo $response;
			}
		}
	}

	/**
	 * This function deletes tempalte.
	 * @return void
	 */
	public function deletetemplateAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$templateId= (int)$this->getRequest()->getParam('id');
			$templateObj = new RCMS_Object_Template_Template($templateId);
			$resultDeleteTemplate = $templateObj->delete();
			$pageObj = new RCMS_Object_Page_Page();
			$pageObj->resetToDefaultTemplate($templateId);
			$result = $templateObj->getTemplateByName('default');
			echo $result->id;
		}
	}

	/**
	 * This function saves settings for gallery.
	 * @return void
	 */
	public function savesettingsforgalleryAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('gallery') != '') {
			$path = $this->_config->website->website->path . $this->_config->website->website->galleries;
			$gallery = $this->getRequest()->getParam('gallery');
			if(file_exists($path . $gallery .'/settings.txt') && is_dir($path . $gallery )) {
				$settings = $this->getRequest()->getParam('thumbnails') . ':';
				$settings .= ($this->getRequest()->getParam('crop')=='true'?'1':'0') . ':';
				$settings .= ($this->getRequest()->getParam('lightbox')=='true'?'1':'0') . ':';
				$settings .= ($this->getRequest()->getParam('caption')=='true'?'1':'0');
				@file_put_contents($path . $gallery .'/settings.txt', $settings);
				echo json_encode(array('save' => true, 'new_gallery' => false)); exit;
			} else {
				$gallery = RCMS_Tools_FilesystemTools::validateName($gallery);
				RCMS_Tools_FilesystemTools::mkDir($path . $gallery);
				RCMS_Tools_FilesystemTools::mkDir($path . $gallery . '/thumbnails/');
				$settings = $this->getRequest()->getParam('thumbnails') . ':';
				$settings .= ($this->getRequest()->getParam('crop')=='true'?'1':'0') . ':';
				$settings .= ($this->getRequest()->getParam('lightbox')=='true'?'1':'0') . ':';
				$settings .= ($this->getRequest()->getParam('caption')=='true'?'1':'0');
				@file_put_contents($path . $gallery .'/settings.txt', $settings);
				echo json_encode(array('save' => true, 'new_gallery' => true, 'gallery' => $gallery)); exit;
			}
		}
	}

	/**
	 * This function loads settings for gallery.
	 * @return void
	 */
	public function loadsettingsforgalleryAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('gallery') != '') {
			$path = $this->_config->website->website->path . $this->_config->website->website->galleries;
			$gallery = $this->getRequest()->getParam('gallery');
			if(file_exists($path . $gallery .'/settings.txt')) {
				$settings = @file_get_contents($path . $gallery .'/settings.txt');
				$array = explode(':', $settings);
				echo json_encode(array(
				'thumbnails'    => $array[0],
				'crop'          => $array[1],
				'lightbox'      => $array[2],
				'caption'       => $array[3]
				)); exit;
			}
		}
	}

	/**
	 * This function deletes picture in gallery.
	 * @return Void
	 */
	public function deletepictureingalleryAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('gallery') != '' && $this->getRequest()->getParam('image') != '') {
			$path = $this->_config->website->website->path . $this->_config->website->website->galleries;
			$gallery = $this->getRequest()->getParam('gallery');
			$image = $this->getRequest()->getParam('image');

			if(is_dir($path . $gallery) && file_exists($path . $gallery . '/' . $image)) {
				RCMS_Tools_FilesystemTools::deleteFile($path . $gallery . '/' . $image);
				RCMS_Tools_FilesystemTools::deleteFile($path . $gallery . '/thumbnails/' . $image);
				$listImages = RCMS_Tools_FilesystemTools::scanDir($path . $gallery . '/thumbnails/');
				$deleteFolder = false;
				if(empty($listImages)) {
					RCMS_Tools_FilesystemTools::deleteFile($path . $gallery . '/settings.txt');
					RCMS_Tools_FilesystemTools::rmDir($path . $gallery . '/thumbnails/');
					RCMS_Tools_FilesystemTools::rmDir($path . $gallery);
					$deleteFolder = true;
				}
				echo json_encode(array('del' => true, 'delete_folder' => $deleteFolder));
			}
			exit;
		}
	}

	/**
	 * This function validates captcha.
	 * @return boolean
	 */
	private function validateCaptcha($captchaInput,$captchaId) {
		$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captchaId);
		$captchaIterator = $captchaSession->getIterator();
		$captchaWord = (isset($captchaIterator['word'])? $captchaIterator['word']:'');
		if( $captchaWord ) {
			if( $captchaInput != $captchaWord ) {
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
	}

	/**
	 * This function inserts payment button.
	 * @return void
	 */
	public function insertpaymentbuttonincontentAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('name') != '' && $this->getRequest()->getParam('content') != '') {
			$name = trim(str_replace(' ', '-', $this->getRequest()->getParam('name')));
			$content = trim($this->getRequest()->getParam('content'));
			$content = preg_replace("~(<script.*>.*</script>)~s", '', $content);
			$ifExisted = (integer) $this->_model->selectIfExistPaymentButtonByName($name);

			if($ifExisted == 1) {
				$this->_model->updatePaymentButton($name, $content);
				echo json_encode(array('update' => true, 'name' => $name)); exit;
			}

			if($ifExisted == 0) {
				$this->_model->insertPaymentButton($name, $content);
				echo json_encode(array('update' => false, 'name' => $name)); exit;
			}
		}
	}

	/**
	 * This function loads payment button.
	 * @return void
	 */
	public function loadpaymentbuttonbynameAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('name') != '') {
			$name = $this->getRequest()->getParam('name');
			$data = $this->_model->selectContentPaymentButtonByName($name);
			echo json_encode(array('content' => $data[0]['value'])); exit;
		}
	}

	/**
	 * This function inserts comment.
	 * @return void

	public function insertcommentincontentAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('topic') != '' && $this->getRequest()->getParam('keyword') != '') {
			$topic = $this->getRequest()->getParam('topic');
			$keyword = $this->getRequest()->getParam('keyword');
			$ifExist = intval($this->_model->selectIfExistTopicAndKeyword($topic, $keyword));
			echo json_encode(array('exist' => $ifExist)); exit;
		}
	}*/

	/**
	 * This function adds a redirect.
	 * @return void
	 */
	public function addredirectAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$this->getRequest()->getParam('topic');
			$originalOldUrl = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('oldUrl'));
			if(isset($originalOldUrl) && $originalOldUrl != '') {
				$originalOldUrl = str_replace(' ', '', trim($originalOldUrl));
			}

			$manualUrl = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('manualurl'));

			if(trim($manualUrl)=="") {
				$pageId = $this->getRequest()->getParam('pageId');
				$pageObj = new RCMS_Object_Page_Page($pageId);
			}else {
				$pageObj = new RCMS_Object_Page_Page();
				$pageObj->setId(rand(10000,999999999));
				//$http = substr($manualUrl, 0,7);
				if(!preg_match('/^https?/', $manualUrl)) {
					$manualUrl = 'http://' . $manualUrl;
				}
				$pageObj->setUrl($manualUrl);
			}
			if(!preg_match('/^https?/', $originalOldUrl)) {
				$originalOldUrl = 'http://' . $originalOldUrl;
			}
			if($originalOldUrl == $this->_websiteUrl || $originalOldUrl . '/' == $this->_websiteUrl) {
				echo 'equal urls'; exit();
			}
			$tmp = $this->processDash($originalOldUrl);
			$res =  str_replace($this->getWebSiteUrl(), '', $tmp);
			$neededUrl = $res; //end($res);
			$oldUrlProcessed = str_replace(' ', '', $neededUrl);
			$originalOldUrl = $this->processDash($originalOldUrl);
			if(!$this->_model->checkExistedRedirect($originalOldUrl)) {
				$oldUrlProcessed = str_replace(".", "\.", $oldUrlProcessed);

				$this->_model->insertRedirect($oldUrlProcessed, $originalOldUrl, $pageObj);
				$cleanResult = $this->_seoParser->cleanBadRedirect($pageObj->getUrl() . '\.html');


				$result = '<div class="redirbord" id="redirect-'.$pageObj->getId().'" >';
				$result .=  '<div class="checkboxes"><input type="checkbox" id="'.$pageObj->getId().'" /></div>';
				$result .=  '<div class="redirecturl">';
				$result.=  $this->divideStringOnParts(urldecode(urldecode($originalOldUrl)));
				$result.=  '<span>&rarr;</span></div>';
				$result.= '<div class="redirecturlimg">';

				$tmp  =  preg_match('/^https?:\/\//', $pageObj->getUrl());
				if($tmp!==0) {
					$newUrl  = $this->divideStringOnParts(urldecode(urldecode($pageObj->getUrl())));
				}else {
					$newUrl  = $this->divideStringOnParts(urldecode(urldecode($this->_websiteUrl.$pageObj->getUrl().".html")));
				}
				$result.= $newUrl;
				$result.= '<a href="javascript:void(0);" title="Delete redirect." onclick="deleteRedirect(';
				$result.= $pageObj->getId();
				$result.= ');"><img src="';
				$result.= $this->_websiteUrl;
				$result.= 'system/images/ico_delete.gif" alt="Delete"/></a></div>';
				$result.= '<p style="clear:both;"></p>';
				$result.= '</div>';
				echo $result;
			}else {
				echo 'exists';
			}
			$this->_seoParser->refreshHtAccess();
		}
	}

	/**
	 * This function adds a deeplink.
	 * @return void
	 */
	public function adddeeplinkAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$name = RCMS_Tools_Tools::stripSlashesIfQuotesOn(trim(strip_tags($this->getRequest()->getParam('name'))));
			$url = RCMS_Tools_Tools::stripSlashesIfQuotesOn(trim(strip_tags($this->getRequest()->getParam('url'))));
			$result = $this->_validateDeeplink($name, $url);

			if(empty($result)) {
				$ifExistName = (integer) $this->_model->selectDeeplinkByName($name);
				if($ifExistName) {
					echo 'exists';
					return;
				}
			} else {
				switch ($result) {
					case 'empty url':
						echo 'empty url';
						break;
					case 'anchor only letters':
						echo 'anchor only letters';
						break;
					case 'anchor at least 2 letters':
						echo 'anchor at least 2 letters';
						break;
					case 'invalid url':
						echo 'invalid url';
						break;
				}
				return;
			}
			$http = substr($url, 0,7);

			if(trim($http) != 'http://') {
				$url = 'http://' . $url;
			}
			$res = explode('/', $url);
			$arr = $res[sizeof($res)-1];
			$page = explode('.', $arr);
			$page = $page[0];

			if(trim($page) == '') {
				echo 'page error';
				return;
			}
			$deeplink = new RCMS_Object_Deeplink_Deeplink();
			$deeplink->setName($name);
			$deeplink->setUrl($url);
			$deeplink->setType($this->getRequest()->getParam('type'));
			$deeplink->setBan(0);
			$deeplink->setNoFollow($this->getRequest()->getParam('nofollow'));
			$flag = $deeplink->save();

			if($flag > 0) {
				$seoParser = new RCMS_Object_Parser_SeoParser();
				//$seoParser->replaceDeeplinksInContent();
				//$seoParser->applyDeeplinks();
				$seoParser->applyDeeplinksPerPage();
				$result = '<div class="mandeepl" style="clear:both;" id="mandeepl-'.$flag.'">';
				$result .= '<div class="mandeepname"><a title="Edit this deeplink" href="javascript:void(0);"';
				$result .= ' onclick="fiilDeeplinkForm('.$flag.');" ';
				$result .= '>'.$this->divideStringOnParts($deeplink->getName(),35).'</a></div>';
				$result .= '<div class="mandeepu"><a title="Jump to URL" href="';
				$result .= $deeplink->getUrl();
				$result .= '" target="_blank">'.$this->divideStringOnParts(urldecode($deeplink->getUrl()),35).'</a></div>';
				$result .= '<div class="mandeepthree">';
				$result .= '<span>';
				if($deeplink->getNoFollow()==1) {
					$result .= 'NF';
				}else {
					$result .= 'F';
				}
				$result .= '</span>';
				$result .= '<span>'.ucfirst($deeplink->getType()).'</span>';
				$result .= '<span><img onclick="deleteDeeplink('.$flag.');" src="'.$this->_websiteUrl.'system/images/ico_delete.gif" title="Delete this deeplink" alt="ico-delete" style="cursor: pointer;"/></span>';
				$result .= '</div>';
				$result .= '<p style="clear:both;"></p>';
				$result .= '</div>';
				echo $result;
			}
		}
	}

	/**
	 * This function fiils deeplink form.
	 * @return void
	 */
	public function fiildeeplinkformAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('id')) {
			$deeplinkObj = new RCMS_Object_Deeplink_Deeplink($this->getRequest()->getParam('id'));
			$tmp = explode('/', $deeplinkObj->getUrl());
			$sizeTmp = sizeof($tmp);
			$p = $tmp[$sizeTmp-1];
			$tmpUrl = explode('.', $p);
			$tmpUrl = urlencode($tmpUrl[0]);
			$page = $this->_model->getPageByUrl($tmpUrl);
			echo $deeplinkObj->getId() . '~' . $deeplinkObj->getName() . '~' . $page['nav_name'] . '~' . $deeplinkObj->getType() . '~' . $deeplinkObj->getNoFollow() . '~' . $deeplinkObj->getUrl();
		}
	}

	/**
	 * This function deletes deeplink.
	 * @return void
	 */
	public function editdeeplinkAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$id = intval($this->getRequest()->getParam('id'));
			$deeplinkObj = new RCMS_Object_Deeplink_Deeplink($id);
			$name = trim(strip_tags($this->getRequest()->getParam('name')));
			$url = trim(strip_tags($this->getRequest()->getParam('url')));
			$http = substr($url, 0,7);

			if(trim($http) != 'http://') {
				$url = 'http://' . $url;
			}
			$res = explode('/', $url);
			$arr = $res[sizeof($res)-1];
			$page = explode('.', $arr);
			$page = $page[0];

			if(trim($page) == '') {
				echo 'page error';
				return;
			}
			$result = $this->_validateDeeplink($name, $url);

			if(empty($result)) {
				$ifExistName = (integer) $this->_model->selectDeeplinkByName($name);
				if($ifExistName > 0 && $name!=$deeplinkObj->getName() ) {
					echo 'exists';
					return;
				}
			} else {
				switch ($result) {
					case 'empty url':
						echo 'empty url';
						break;
					case 'anchor only letters':
						echo 'anchor only letters';
						break;
					case 'anchor at least 2 letters':
						echo 'anchor at least 2 letters';
						break;
					case 'invalid url':
						echo 'invalid url';
						break;
				}
				return;
			}
			$deeplinkObj->setName($name);
			$deeplinkObj->setType($this->getRequest()->getParam('type'));
			$deeplinkObj->setUrl($url);
			$deeplinkObj->setNoFollow($this->getRequest()->getParam('nofollow'));
			$deeplinkObj->setBan(0);
			$flag =  $deeplinkObj->save();

			if($flag > 0) {
				$seoParser = new RCMS_Object_Parser_SeoParser();
				$seoParser->replaceDeeplinksInContent();
			}
			$result = $deeplinkObj->getId()."~";
			$result .= '<div class="mandeepname"><a title="Edit this deeplink" href="javascript:void(0);"';
			$result .= ' onclick="fiilDeeplinkForm('.$deeplinkObj->getId().');" ';
			$result .= '>'.$this->divideStringOnParts($deeplinkObj->getName(),35).'</a></div>';
			$result .= '<div class="mandeepu"><a title="Jump to URL" href="';
			$result .= $deeplinkObj->getUrl();
			$result .= '" target="_blank">'.$this->divideStringOnParts($deeplinkObj->getUrl(),35).'</a></div>';
			$result .= '<div class="mandeepthree">';
			$result .= '<span>';

			if($deeplinkObj->getNoFollow() == 1) {
				$result .= 'NF';
			} else {
				$result .= 'F';
			}
			$result .= '</span>';
			$result .= '<span>'.ucfirst($deeplinkObj->getType()).'</span>';
			$result .= '<span><img onclick="deleteDeeplink('.$deeplinkObj->getId().');" src="'.$this->_websiteUrl.'system/images/ico_delete.gif" title="Delete this deeplink" alt="ico-delete" style="cursor: pointer;"/></span>';
			$result .= '</div>';
			$result .= '<p style="clear:both;"></p>';
			echo $result;
		}
	}

	/**
	 * This function deletes deeplink.
	 * @return void
	 */
	public function  deletedeeplinkAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('id')) {
			$id = intval($this->getRequest()->getParam('id'));
			if($id > 0) {
				$seo = new RCMS_Object_Parser_SeoParser();
				$seo->deleteDeeplinkFromContent($id);
				$deeplink = new RCMS_Object_Deeplink_Deeplink($id);
				$deeplink->delete();
				echo $id; exit();
			}
		}
	}

	/**
	 * Deletes redirect.
	 * @return void
	 */
	public function deleteredirectAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$pageId = $this->getRequest()->getParam('pageId');
			if($pageId) {
				$this->_model->deleteRedirect($pageId);
				echo $pageId;
			}
			$seoParser = new RCMS_Object_Parser_SeoParser();
			$seoParser->refreshHtAccess();
		}
	}

	/**
	 * Deletes redirects.
	 * @return void
	 */
	public function deletemassredirectsAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$result = array();
			$arrIds = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('arrIds')));

			if($arrIds) {
				foreach ($arrIds as $key=>$value) {
					if($value) {
						$this->_model->deleteRedirect($value);
						$result[]=$value;
					}
				}
			}
			echo json_encode($result);
			$seoParser = new RCMS_Object_Parser_SeoParser();
			$seoParser->refreshHtAccess();

		}
	}

	/**
	 * This functin returns array of vars.
	 * @return void
	 */
	public function getvarsAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$varrialbes = $this->_model->getAdditionalVarriablesNames();
		//check if rrs feeds exists. If yes create a variables for them
		$rssFeedVars = $this->_getRssFeedsList();
		if(!empty ($rssFeedVars)) {
			$varrialbes = array_merge($varrialbes, $rssFeedVars);
		}
		if(empty($varrialbes)) {
			echo 'no_vars';
			exit;
		}
		echo json_encode($varrialbes);
	}

	/**
	 * This function devides string on parts of setted length.
	 * @param string $string
	 * @param integer $length
	 * @return string
	 */
	public function divideStringOnParts($string, $length = 50) {
       /* $result = '';
        $partsCount = (int)(strlen($string)/$length);
        for($i=0;$i<$partsCount+1;$i++) {
			//$result .= substr($string,($i*$length),$i+$length) . '<br/>';
            $result .= substr($string,($i*$length),$i+$length) . "<br>";
        }
        $end = sizeof($result)-6;
        $result = substr($result, 0,$end);
        return $result;*/
		return $string;
	}

	/**
	 * This function returns array of Rss List.
	 * @return array
	 */
	private function _getRssFeedsList() {
		$xmlFilesListVars = array();
		$tmpXmlFilesList = RCMS_Tools_FilesystemTools::findFilesByExt('feeds/', 'xml');
		if(empty($tmpXmlFilesList)) {
			return;
		}
		foreach ($tmpXmlFilesList as $xmlFile) {
			if(stristr($xmlFile, 'sitemap') || stristr($xmlFile, 'sitemapnews') || stristr($xmlFile, 'sitemapindex')) {
				continue;
			}
			$xmlFilesListVars[] = 'rssfeed:' . str_replace('.xml', '', $xmlFile);
			if(!stristr($xmlFile, 'full')) {
				$xmlFilesListVars[] = 'newslist:' . str_replace('.xml', '', $xmlFile);
			}
		}
		return $xmlFilesListVars;
	}

	/**
	 * This functin is validate name and url.
	 * @param string $name
	 * @param string $url
	 * @return array
	 */
	private function _validateDeeplink($name, $url) {
		$url = str_replace('http://', '', $url);
		$url = str_replace('https://', '', $url);
		$url = str_replace('http:/', '', $url);
		$url = str_replace('https:/', '', $url);

		if($url === '') {
			return 'empty url';
		}
		if(!preg_match('/^[\p{L}\p{M}\p{P}A-z0-9.-_\s]{1,255}+$/u', $name)) {
			return 'anchor only letters';
		}
		if (!preg_match('/^[\p{L}\p{M}\p{P}a-z0-9-.\/\?\&=]{1,210}+$/u', $url)) {
			return 'invalid url';
		}
	}
	/**
	 * Deletes user.
	 * @return void
	 */
	public function deleteuserAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') > 0 ) {
			$user = new RCMS_Object_User_User($this->getRequest()->getParam('id'));
			if(is_object($user) && $user->getId() > 0) {
				$done = $user->delete(); echo $done;
			} else {
				echo '0';
			}
		}
		exit;
	}

	/**
	 * Loads user.
	 * @return void
	 */
	public function loaduserAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') > 0 ) {
			$user = new RCMS_Object_User_User($this->getRequest()->getParam('id'));
			if(is_object($user) && $user->getId() > 0) {
				echo json_encode(array(
				'nickname'  => $user->getNickName(),
				'login'     => $user->getLogin(),
				'password'  => $user->getPassword(),
				'email'     => $user->getEmail(),
				'role'      => $user->getRoleId())
				);
			} else {
				echo json_encode(array());
			}
		}
		exit;
	}

	/**
	 * Replaces '///' to '//'
	 * @param string $string
	 * @return string
	 */
	public function processDash($str) {
		$pos = strstr($str, '///');
		if($pos) {
			return  $this->processDash(str_replace('///', '//', $str));
		}
		return $str;
	}

	/**
	 * Run Google wheel to find a sinonyms.
	 * @return void
	 */
	public function rungooglewheelAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if($this->getRequest()->isPost()) {
			$inspWord = urlencode(strip_tags($this->getRequest()->getParam('inspired')));
			$firstWheelSearchUrl = 'http://www.google.com/search?q=' . $inspWord . '&hl=en&tbo=1&tbs=ww:1';
			$result = $this->_runCurlForWheel($firstWheelSearchUrl);
			if($result) {
				if (preg_match('/"r":\[(.*?)\]}\)/', $result, $matches)) {
					$response = str_replace('"', '', $matches[1]);
					$secondResponse = explode(',', $response);
					$thirdResponse = '';
					foreach ($secondResponse as $key => $value) {
						$encodedValue = urlencode($value);
						$secondWheelSearchUrl = 'http://www.google.com/search?q=' . $encodedValue . '&hl=en&tbo=1&tbs=ww:1';
						$secondResult = $this->_runCurlForWheel($secondWheelSearchUrl);
						if($secondResult) {
							if (preg_match('/"r":\[(.*?)\]}\)/', $secondResult, $matches2)) {
								$response .= ',' . str_replace('"','',$matches2[1]);
							}
						}
					}
					$thirdResponse = array_unique(explode(',', $response));
					asort($thirdResponse);
					$finalResult = '<span>Google wheel is answering:</span><br/><br/><ul class="whole-phrase">';
					foreach ($thirdResponse as $key => $value) {
						$finalResult .= '<li>'.utf8_decode($value).'</li>';
					}
					$finalResult.='</ul>';
				}
			}
			echo $finalResult;
		}
		exit;
	}

	/**
	 * Execute curl for google wheel.
	 * @param string $searchUrl
	 * @return string
	 */
	private function _runCurlForWheel($searchUrl) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $searchUrl);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		curl_setopt($ch, CURLOPT_REFERER, $searchUrl);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}

	////////////////**********Form Hadling**************//////////////////////////////////
	/**
	 * This function generates email body for auto reply message.
	 * @param array $post
	 * @param RCMS_Object_Page_Page $pageObj
	 * @return string
	 */
	private function _generateFormEmaiToAdminBody($post, RCMS_Object_Page_Page $pageObj) {
		$referer = $this->_session->userReferrerUrl; 		
        $body = "<h3>New message posted on " . $this->getWebSiteUrl().$pageObj->getUrl() . ".html .</h3> <br /><h3>Referer: ".$referer."</h3><br />";
		$content = '';
		if($post) {
			foreach($post as $key=>$value) {
				if(trim($key)!='controller' && trim($key)!='action' && trim($key)!='module' && trim($key)!='pageId' && trim($key)!='formId' && trim($key)!='captchaId' && trim($key)!='captcha' && trim($key)!='input' && trim($key)!=trim($value)) {
					if(is_array($value)) {
						$value = implode(', ', $value);
                    }
                    $modelConfig = new Backend_ConfigModel;
                    $configData  = $modelConfig->selectAll();
                    $language    = $configData['translate_language'];
                    if($language == 'french' && $key == 'name'){
                        $key = 'nom';
                    }
                    if($language == 'french' && $key == 'subscribeCC'){
                        $key = 'Souscription à Constant Contact';
						$value = 'oui';
                    }
					if($language == 'english' && $key == 'subscribeCC'){
                        $key = 'Subscribe Constant Contact'; 
						$value = 'yes';
                    }
//                    if($language == 'german' && $key == 'name'){
//                        $key = 'num';
//                    }
//                    if($language == 'german' && $key == 'subscribeCC'){
//                        $key = 'num';
//                    }
//                    if($language == 'italian' && $key == 'name'){
//                        $key = 'num';
//                    }
//                    if($language == 'italian' && $key == 'subscribeCC'){
//                        $key = 'num';
//                    }
//                    if($language == 'portuguese' && $key == 'name'){
//                        $key = 'num';
//                    }
//                    if($language == 'portuguese' && $key == 'subscribeCC'){
//                        $key = 'num';
//                    }
//                    if($language == 'russian' && $key == 'name'){
//                        $key = 'num';
//                    }
//                    if($language == 'russian' && $key == 'subscribeCC'){
//                        $key = 'num';
//                    }
//                    if($language == 'spanish' && $key == 'name'){
//                        $key = 'num';
//                    }
//                    if($language == 'spanish' && $key == 'subscribeCC'){
//                        $key = 'num';
//                    }
                	$content .= trim($key) . ' : ' . (($value)? trim($value) : 'empty.') . "<br />";
				}
			}
		}
		return $body . '<div style="background: #FFFFD3;">' . $content . '</div>';
	}


	/**
	 * This function generates email body for auto reply message
	 * @param  RCMS_Object_Form_Form $formObj
	 * @return string
	 */
	private function _generateFormEmaiAutoReplyBody(RCMS_Object_Form_Form $formObj=null) {
		if($formObj!=null && $formObj->getEmailMessage()) {
			return $formObj->getEmailMessage();
		} else {
			return 'Thank you for posting a message.';
		}
	}

	/**
	 * @method This function checks if smtp allowed in config
	 * @return Boolean
	 */
	private function _checkSmtpAllowedInConfig() {
		if(isset($this->_configTableArray['use_smtp']) && $this->_configTableArray['use_smtp'] == 1 &&
			isset($this->_configTableArray['smtp_login']) && $this->_configTableArray['smtp_login'] != '' &&
			isset($this->_configTableArray['smtp_password']) && $this->_configTableArray['smtp_password'] != '') {
			return true;
		}
		return false;
	}

	/**
	 * This function checks if smtp allowed in Form Object
	 * @param RCMS_Object_Form_Form $formObj
	 * @return boolean
	 */
	private function _checkSmtpAllowedInFormObj(RCMS_Object_Form_Form $formObj) {
		if($formObj->getUseSMTP()) {
			return true;
		}
		return false;
	}


	/**
	 * This function returns email to FORM settings.
	 * @param RCMS_Object_Form_Form $formObj
	 * @return string
	 */
	private function _getEmailTo(RCMS_Object_Form_Form $formObj=null) {
		if($formObj!=null) {
			if($formObj->getEmail()) {
				return $formObj->getEmail();
			}
			return $this->_adminEmail;
		}else {
			return $this->_adminEmail;
		}

	}

	/**
	 * This function returns email from FORM settings.
	 * @param RCMS_Object_Form_Form $formObj
	 * @return string
	 **/
	private function _getEmailFrom(RCMS_Object_Form_Form $formObj) {
		if($formObj != null) {
			if($formObj->getEmailFrom()) {
				return $formObj->getEmailFrom();
			}
		}
		return false;
	}

	/**
	 * @method This function put message in session and redirects to page
	 * @return RCMS_Object_Form_Form $formObj
	 * @return string $messageType
	 * @return void
	 **/
	private function _showEmailMessage(RCMS_Object_Form_Form $formObj,$messageType) {
		if($messageType == 'success') {
			if($formObj && trim($formObj->getSuccessMessage()) != '') {
				$successMessage = trim($formObj->getSuccessMessage());
			} else {
				$successMessage = 'Email was sent.';
			}

			$succesTrackingPageUrl = '';
			if($formObj->getTrack()) {
				$trackingData = $formObj->getTrackingData();
				$thxPage = new RCMS_Object_Page_Page($trackingData['thxPageId']);
				$succesTrackingPageUrl = $thxPage->getUrl();
				unset ($thxPage);
			}

			$successMsgData = array(
				'msg'        => $successMessage,
				'thxPageUrl' => $succesTrackingPageUrl
			);

			$this->_session->formSuccessMessage = $successMsgData;
		}
		if($messageType == 'error') {
			if(trim($formObj->getErrorMessage()) != '') {
				$errorMessage = trim($formObj->getErrorMessage());
			} else {
				$errorMessage = 'Sending failed. Check your SMTP settings.';
			}
			$this->_session->formErrorMessage = $errorMessage;
		}
		if($messageType == 'captcha') {
			$this->_session->formCaptchaNotValid = 'Verification code is incorrect. Please try again.';
		}
		if($messageType == 'smtp denied') {
			$this->_session->formSmtpMessage = 'Sending email failed.<br/> Check your smtp settings in manage config screen.';
		}
		if($messageType == 'email not valid') {
			$this->_session->formEmailNotValid = 'Entered Email is not valid.';
		}
		$this->_redirect($this->getWebSiteUrl().$this->_pageUrl);
		exit;
	}


	/**
	 * @method This function generates value for to/from comment variable
	 * @return string
	 **/
	private function _generateSmtpComment($userName,$email) {
		if($userName) {
			return $userName;
		} else {
			$arr = explode('@', $email);
			return $arr[0];
		}
	}

/*!!!!!! THIS IS NOT FUNCTION FOR AJAX. !!!!!!!*/
	/**
	 * @method This function handles form submit
	 * @return void
	 */
	public function formhandlerAction() {
		$this->_initSmtp();
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('formId') > 0 && $this->getRequest()->getParam('pageId') > 0 ) {
			//default case if we do not use captcha so we put it in true
			$captchaValid = true;
			$post = $this->getRequest()->getParams();
            $formId = $this->getRequest()->getParam('formId');
            $model = new Backend_AjaxModel();
            if ($this->getRequest()->getParam('subscribeCC') == 1) {
                if($model->selectConstantContactFlag($formId) == 1) {
                    $constantContactList = unserialize($model->selectConstantContactList($formId));
                    $constantLogin = $model->selectConstantContactLogin();
                    $constantPassword = $model->selectConstantContactPassword();
                    $apikey = $model->selectConstantContactApikey();
                    $constantContactObjects = new RCMS_Object_ConstantContact_ConstantContact($constantLogin,$constantPassword, $apikey);
                    $constantContactObj = new CC_Contact($constantLogin,$constantPassword, $apikey);
                    $constantcontactArray = array();
                    $constantcontactArray["email_address"] = $this->getRequest()->getParam('email');
                    $constantcontactArray["first_name"] = $this->getRequest()->getParam('name');
                    $constantcontactArray["lists"] = $constantContactList;
                    $contactXML = $constantContactObj->createContactXML(null,$constantcontactArray);
                    $constantContactObj->addSubscriber($contactXML);
                }
            }           
			$formObj = new RCMS_Object_Form_Form($this->getRequest()->getParam('formId'));
			$pageObj = new RCMS_Object_Page_Page($this->getRequest()->getParam('pageId'));
			$this->_pageUrl = $pageObj->getUrl() . '.html';
			//check if captcha set and valid
			if(isset($post['captchaId']) && $post['captchaId'] != '') {
				$captcha= $this->getRequest()->getParam('captcha');
				$captchaInput = $captcha['input'];
				$captchaId = $this->getRequest()->getParam('captchaId');

				if( !$this->validateCaptcha($captchaInput,$captchaId) ) {
					$captchaValid = false;
				}
			}
			if($captchaValid) {
				if(isset($post['name']) && trim($post['name']) != '' ) {
					$userName = trim($post['name']);
				} else {
					$userName = false;
				}
				if(isset($post['email']) && trim($post['email']) != '') {
					$emailFrom = $post['email'];
					$validator = new Zend_Validate_EmailAddress();
					if(!$validator->isValid($emailFrom)) {
						$this->_showEmailMessage($formObj,'email not valid');
					}
				} else {
					$emailFrom = 'userwithnoemail@userwithnoemail.com';
				}
				if( isset($post["dealeremail"]) && ($post["dealeremail"] != "")) {
					$ccMail = trim($post["dealeremail"]);
				}
				else{$ccMail = null;}
				///////////////////////////////////////////////////////////////////////
				$useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
				$useSmtpInForm = $this->_checkSmtpAllowedInFormObj($formObj);
				if($useSmtpInForm==1 && $useSmtpInConfig==0 ) {
					$this->_showEmailMessage($formObj,'smtp denied');
				}
				if($useSmtpInConfig && $useSmtpInForm) {
					$useSmtp = true;
				} else {
					$useSmtp = false;
				}
				//sending email to admin

				//attachments
				$attachemt = $this->_createMailAttachment();


				$to = $this->_getEmailTo($formObj);
				$toComment = $this->_smtpHost;
				$from = $emailFrom;
				$fromComment =  $this->_generateSmtpComment($userName,$emailFrom);

				$subject = 'A new message was posted on ' . $this->_domain;
				$body =  $this->_generateFormEmaiToAdminBody($post,$pageObj);
				$emailAdminSent = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp, $attachemt, $ccMail);
				/////////////////////////
				//sending auto reply message to user
				$to = $emailFrom;
				$toComment = $this->_generateSmtpComment($userName,$emailFrom);
				$from = $this->_getEmailFrom($formObj);
				$fromComment = $this->_smtpHost;
				$subject = (!$formObj->getAutoReplySubj()) ? 'A message from ' . $this->_smtpHost : $formObj->getAutoReplySubj();
				$body =  $this->_generateFormEmaiAutoReplyBody($formObj);
				$emailAutoReplySent = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);

				if($emailAdminSent) {
					$this->_showEmailMessage($formObj,'success');
				} else {
					$this->_showEmailMessage($formObj,'error');
				}
			} else {
				$this->_showEmailMessage($formObj,'captcha');
			}
		}
		$this->_redirect($this->getWebSiteUrl().$this->_pageUrl);
	}

    public function constantcontactlistAction(){
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        if($this->getRequest()->isPost()){
            $constantLogin = $this->getRequest()->getParam('constantContactLogin');
            $constantPassword = $this->getRequest()->getParam('constantContactPassword');
            $apikey = $this->getRequest()->getParam('constantContactApikey');
            $constantContactObjects = new RCMS_Object_ConstantContact_ConstantContact($constantLogin,$constantPassword, $apikey);
            $constantContactListOBJ = new CC_List($constantLogin,$constantPassword, $apikey);
            $constantContactObj = new CC_Contact($constantLogin,$constantPassword, $apikey);
            $allLists = $constantContactListOBJ->getLists();
            if (count($allLists)==0){
               $emptyList = 'EmptyList or wrong parameters';
                echo json_encode($emptyList);
            }
            else{
            echo json_encode($allLists);
            }

        }

    }
   	private function _createMailAttachment() {
		$uploaded   = array();
		$attachment = array();
		$websitePathTemp = unserialize(Zend_Registry::get('config'))->website->website->path . 'tmp/';
		$uploader = new Zend_File_Transfer_Adapter_Http();
		$uploader->setDestination($websitePathTemp);
		//$uploader->addValidator('Count', false, '3');
		$uploader->addValidator('Extension', false, RCMS_Object_QuickConfig_QuickConfig::$attachmentsFileTypes);

		$files = $uploader->getFileInfo();
		foreach($files as $file => $fileInfo) {
			if($uploader->isValid($file)) {
				$uploader->receive($file);
				//$uploaded[] = $uploader->getFileName($file);
				$at              = new Zend_Mime_Part(file_get_contents($uploader->getFileName($file)));
				$at->type        = $uploader->getMimeType($file);
				$at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
				$at->encoding    = Zend_Mime::ENCODING_BASE64;
				$at->filename    = $fileInfo['name'];
				$attachment[]    = $at;
				unset($at);
			}
		}
		return $attachment;
	}


	/**
	 * @method This function sends email through smtp or regular email
	 * @param String $to
	 * @param String $toComment
	 * @param String $from
	 * @param String $fromComment
	 * @param String $subject
	 * @param String $body
	 * @param Integer $useSmtp
	 * @return Boolean
	 */
	public function sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp, $attachment = null, $ccEmail = null) {
		if($useSmtp) {
			$tr = new Zend_Mail_Transport_Smtp($this->_smtpHost, $this->_smtpConfigArray);
			Zend_Mail::setDefaultTransport($tr);
		}
		$mailer = new Zend_Mail( 'utf-8' );
		$mailer->addTo($to,$toComment);
		if($ccEmail !== null) {
			$mailer->addCc($ccEmail,$fromComment);
		}
		$mailer->setFrom($from,$fromComment);
		$mailer->setSubject($subject);
		$mailer->setBodyHtml($body);
		if($attachment !== null) {
			if(is_array($attachment)) {
				foreach($attachment as $at) {
					$mailer->addAttachment($at);
				}
			}
			else {
				$mailer->addAttachment($attachment);
			}
		}
		try {
			$mailer->send();
			return true;
		} catch (Exception $e) {
			return false;
		}
	}

	////////////////////*********COMMENTS HANDLER ACTION**************//////////////////////////////////
	/**
	 * @method This function generates body of email to admin in order to inform that a new comment was added
	 * @param <String> $sign
	 * @param <String> $email
	 * @param <String> $content
	 * @return <String>
	 */
	private function _generateEmailBodyForAdminComments($sign,$email,$content) {
		if($sign && $email && $content) {
			$sign = ucfirst(strtolower(trim($sign)));
			$email = trim($email);
			$content = trim($content);
			return 'Hello,  ' . $sign . "  '<".$email.">' posted a new comment on ".$this->getWebSiteUrl().$this->_pageUrl.". \nPlease login to the system to moderate this comment.\r\nMessage:\n".$content;
		}
		return '';
	}

	/**
	 * @method This function generates body of email to users in order to inform them about a new comment on a subject metter
	 * @param String $sign
	 * @param String $email
	 * @return String
	 */
	private function _generateEmailBodyForNotifyComments($sign, $email) {
		return "---- No need to reply to this email. --- \n \n \nHello,  ".$sign."  '<".$email.">', this is an automated message to inform you of a new comment posted on ".$this->_websiteUrl.$this->_pageUrl."\n\n\n---- No need to reply to this email. ---\n";
	}

	/**
	 * @method This function generates body of email to user in order to inform him that his comment was published
	 * @param RCMS_Object_Comment_Comment $commentObj
	 * @return String
	 */
	private function _generateEmailBodyForPublishingComment(RCMS_Object_Comment_Comment $commentObj) {
		return "---- No need to reply to this email. --- \n \n \nHello,  ".$commentObj->getUserSign()."  '<".$commentObj->getUserEmail().">', this is an automated message to inform you that your comment was published on ".$this->_websiteUrl.$this->_pageUrl."\n\n\n---- No need to reply to this email. ---\n";
	}

	/**
	 * @method This function adds new comment
	 * @return Void
	 */
	public function addcommentAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_initSmtp();

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('content') != ''
			&& $this->getRequest()->getParam('sign') != '' && $this->getRequest()->getParam('email') != '') {
			$content = ($this->getRequest()->getParam('content'))? htmlspecialchars($this->getRequest()->getParam('content')) : '';
			$sign = ($this->getRequest()->getParam('sign'))? htmlspecialchars($this->getRequest()->getParam('sign')) : '';
			$email = ($this->getRequest()->getParam('email'))? htmlspecialchars($this->getRequest()->getParam('email')) : '';
			$website = ($this->getRequest()->getParam('website'))? htmlspecialchars($this->getRequest()->getParam('website')) : '';
			$containerId = ($this->getRequest()->getParam('containerId'))? $this->getRequest()->getParam('containerId') : 0;
			$topic = ($this->getRequest()->getParam('topic'))? $this->getRequest()->getParam('topic') : '';
			$keyword = ($this->getRequest()->getParam('keyword'))? $this->getRequest()->getParam('keyword') : '';
			$publishedbydefault = ($this->getRequest()->getParam('publishedbydefault'))? $this->getRequest()->getParam('publishedbydefault') : 0;
			$notify = ($this->getRequest()->getParam('notify'))? $this->getRequest()->getParam('notify') : 0;
			$captchaInput = htmlspecialchars($this->getRequest()->getParam('captcha-input'));
			$captchaId = $this->getRequest()->getParam('captcha-id');
			$this->_pageUrl =  ($this->getRequest()->getParam('requestedPage'))? str_replace('.html', '', $this->getRequest()->getParam('requestedPage')) . '.html' : '';
			if($notify == 'true') {
				$notify =1;
			} else {
				$notify =0;
			}
			if( !$this->validateCaptcha($captchaInput,$captchaId) ) {
				$captchaId = RCMS_Tools_Tools::generateCaptcha();
				echo 'captacha error~' . $sign . '~' . $email . '~' . $website . '~' . $notify . '~' . $content . '~' . $captchaId;
				exit();
			}
			$commentObj = new RCMS_Object_Comment_Comment();
			$commentObj->setContent($content);
			$commentObj->setConteinerId($containerId);
			$commentObj->setDate(date("Y-m-d H:i:s"));
			$commentObj->setUserId(0);
			$commentObj->setUserEmail($email);
			$commentObj->setAbuse(0);
			$commentObj->setUserSign($sign);
			$commentObj->setUserWebsite($website);
			$commentObj->setPublish($publishedbydefault);
			$commentObj->setRank(0);
			$commentObj->setTopic($topic);
			$commentObj->setKeyword($keyword);
			$commentObj->setNotify($notify);
			$result = false;
			$newCommentId = $commentObj->save();
			$commentsToNotifyArray = $this->_model->selectCommentsToNotify($commentObj->getConteinerId());
			$useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
			if($useSmtpInConfig) {
				$useSmtp = true;
			} else {
				$useSmtp = false;
			}
			$adminEmail = $this->_adminEmail;
			$to = $adminEmail;
			$toComment = $this->_smtpHost;
			$from = $commentObj->getUserEmail();
			$fromComment = $this->_smtpHost;
			$subject = 'A new comment was posted on ' . $this->_smtpHost;
			$body =  $this->_generateEmailBodyForAdminComments($sign,$email,$content);
			$emailAdminSent = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
			if($commentsToNotifyArray) {
				foreach ($commentsToNotifyArray as $comment) {
					$to = $comment['user_email'];
					$toComment = $this->_smtpHost;
					$from = $adminEmail;
					$fromComment = $this->_smtpHost;
					$subject = "A new comment was posted on ".$this->_smtpHost;
					$body =  $this->_generateEmailBodyForNotifyComments($comment['user_sign'],$comment['user_email']);
					$this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
				}
			}
			$style = ($commentObj->getPublish()) ? 'style="border:1px solid #DDD;"' : 'style="border:1px dotted red"';
			if($newCommentId) {
                $publishingDate = RCMS_Tools_Tools::proccessPublishingDateCommentsFromSql($commentObj->getDate());
				$result  = '<li '.$style.' id="comment-item-li-'.$newCommentId.'"  class="comments-block" > ';
				$result .= '<abbr class="comment-timestamp" title="'.$publishingDate.'">';
				$result .=  $publishingDate;
				$result .= '</abbr>';
                $result .= '<a class="comment-author" rel="nofollow" title="'.$commentObj->getUserWebsite().'" href="'.$commentObj->getUserWebsite().'">';
				$result .=  ucfirst(strtolower($commentObj->getUserSign()));
				$result .= '</a>';
				$result .= ' says:';
//				$result .= ' <a class="commentreply" href="';
//				$result .= $this->view->websiteUrl.$this->_pageUrl."#comment-form";
//				$result .= '" title="Reply to this comment">Reply';
//				$result .= '</a>';
				$result .= '<blockquote class="comment-body">';
				$result .= $commentObj->getContent();
				$result .= '</blockquote>';
				if($this->_session->isLogged) {
					$result .= '<a class="deletecomment" title="Delete this comment" onclick="if(confirm(\'Do you really want to delete this comment?\')){deleteComment('.$newCommentId.'); } " href="javascript:void(0);" style="border:none;position:absolute;top:1px;right:4px" >';
					$result .= '<img style="width:16px;border:none;" alt="Delete this comment" src="';
					$result .= $this->view->websiteUrl.'system/images/ico_delete.gif"/>';
					$result .= '</a>';
				}
				$result .= '</li>';
			}
			$captchaId = RCMS_Tools_Tools::generateCaptcha();
			echo $result . '~' . $captchaId;
		}
	}

	/**
	 * @method This function deleting comment
	 * @return Void
	 */
	public function deletecommentAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') != '') {
			$commentId = $this->getRequest()->getParam('id');
			$commentObj = new RCMS_Object_Comment_Comment($commentId);
			if($commentObj->delete()) {
				echo 'Comment ' . $commentId . ' was deleted.';
			}
		}
	}

	/**
	 * @method This function publishing commnet
	 * @return Void
	 */
	public function  publishcommentAction() {
		$this->_initSmtp();
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') != '') {
			$commentId = $this->getRequest()->getParam('id');
			$commentObj = new RCMS_Object_Comment_Comment($commentId);
			$commentObj->setPublish(1);
			$commentObj->save();
			echo $commentId;
			$useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
			if($useSmtpInConfig) {
				$useSmtp = true;
			} else {
				$useSmtp = false;
			}
			$adminEmail = $this->_adminEmail;
			$to = $commentObj->getUserEmail();
			$toComment = $commentObj->getUserSign();
			$from = $adminEmail;
			$fromComment = $this->_smtpHost;
			$subject = 'Your comment was published on ' . $this->_smtpHost;
			$body =  $this->_generateEmailBodyForPublishingComment($commentObj);
			$emailAdminSent = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
		}
	}


	public function cachepluginAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if($this->getRequest()->isPost() && $this->getRequest()->getParam('plugin') != '') {
			$pluginName = trim($this->getRequest()->getParam('plugin'));
			$result = $this->_model->selectPlugin($pluginName);
			if(!$result) {
				echo 'error';
				return;
			}
			$pluginObj	= new RCMS_Object_Plugin_Plugin($result['id']);

			if($pluginObj->getCache()==0) {
				$pluginObj->setCache(1);
			}else {
				$pluginObj->setCache(0);
			}
			$pluginObj->save();
		}
	}

	public function sendrecoveringlinkAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
		//delete all old links
			$this->_model->deleteAllOldLinks();
			$emailExistsInDB = false;
			$sendEmail = false;
			$email = $this->getRequest()->getParam('email');

			/*Start Step 1*/
			$test = $this->_model->selectUserEmail($email);
			if($test) {
				$emailExistsInDB = true;
			}
			/*End Step 1*/
			/*Start Step 2*/
			if($emailExistsInDB) {
				$randEmailLinkValue = rand(0, 999999);
				$this->_initSmtp();
				$useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
				if($useSmtpInConfig) {
					$useSmtp = true;
				} else {
					$useSmtp = false;
				}
				$to=$email;
				$toComment = "";
				$from = $this->_adminEmail;
				$fromComment = "";
				$subject = "Recovering Password";
				$body = "Please click on the following link to re-set your password to ".$this->getWebSiteUrl().":".
                    "\n\n ".$this->getWebSiteUrl()."sys/backend_ajax/resetpassword?link=".$randEmailLinkValue."&e=".$email."\n\n".
                    "If you received this message and did not request a password re-set, please contact " . $this->_adminEmail;

				$sendEmail = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
				if($sendEmail) {
					$this->_model->insertPasswordRecovering($randEmailLinkValue);
					echo "success";
				}else
				{
					echo "error";
				}
			}else
			{
				echo "email does not exist";
			}
			/*End Step 2*/
		}
	}
	public function resetpasswordAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_model->deleteAllOldLinks();
		$link = $this->getRequest()->getParam('link');
		$email = $this->getRequest()->getParam('e');
		if($link) {
			$flag = $this->_model->selectPasswordRecovering($link);
			if($flag) {
				$this->_initSmtp();
				$useSmtpInConfig = $this->_checkSmtpAllowedInConfig();

				if($useSmtpInConfig) {
					$useSmtp = true;
				} else {
					$useSmtp = false;
				}

				$userId = $this->_model->selectUserEmail($email,true);
				$userObj = new RCMS_Object_User_User($userId);
				$newPassword = $this->generateRandomString(8);
				$userObj->setPassword(md5($newPassword));
				$userObj->save();

				$to = $email;
				$toComment = "";
				$from = $this->_adminEmail;
				$fromComment = "";
				$subject = "Recovering Password Confirmation";
				$body = "Thank you for confirming your ".$this->getWebSiteUrl()." password reset.  Your new password is listed below.\n";
				$body .= "Log in: ".$userObj->getLogin()." .\n";
				$body .= "New password: ".$newPassword."\n";
				$body .= "Login at ".$this->getWebSiteUrl()." and change your password by clicking on the green “Show/Hide panel” box in the upper right-hand corner (appears after log-in).
                    Select change password under preferences.  Please contact ".$this->_adminEmail." with any questions.";
				$sendEmail = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
				if($sendEmail) {
					$this->_model->deletePasswordRecoveringLink($link);
				}
			}
			$this->_redirect($this->view->websiteUrl."sys/login/index?recovering=success");
		}
	}

	public function generateRandomString($length = 10, $letters = '1234567890qwertyuiopasdfghjklzxcvbnm') {
		$s = '';
		$lettersLength = strlen($letters)-1;

		for($i = 0 ; $i < $length ; $i++) {
			$s .= $letters[rand(0,$lettersLength)];
		}
		return $s;
	}

        public function storelasturlAction() {
            $this->_helper->getHelper('layout')->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);

            if ($this->getRequest()->isPost()){
                $this->_session->lastUrl = $this->getRequest()->getParam('lastUrl');
            }
			$config = $this->_model->getShoppingConfig();
			if ($config['use_https'] == 1) {
				$url = preg_replace('/http:\/\//', 'https://', $this->getWebSiteUrl().'cart');
			}
			else {
				$url = $this->getWebSiteUrl().'cart';
			}
            echo json_encode(array('done'=>true, 'url'=>$url));
        }

	public function storeprodfilterAction() {
		$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
		if($this->getRequest()->isPost()) {
			$this->_session->productFilter = $this->getRequest()->getParam('productFilter');
		}
	}

    public function addreviewAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_initSmtp();

        $userRole = isset($this->_session->currentUser)?unserialize($this->_session->currentUser)->getRoleId():0;
        $isAdmin = ($userRole == 3 || $userRole == 1 ? true : false);

        if($this->getRequest()->isPost()) {
			$productId = htmlspecialchars(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('productId')));
            $userName = htmlspecialchars(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('name')));
            $userEmail = htmlspecialchars(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('email')));
            $userWebsite = htmlspecialchars(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('website')));
            $userWebsite = strpos($userWebsite, 'http://') !== 0 ? 'http://'.str_replace('http://', '', $userWebsite) : $userWebsite;
            $reviewTopic = htmlspecialchars(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('topic')));
            $reviewContent = htmlspecialchars(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('review_content')));
            $captchaInput = htmlspecialchars(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('captcha_input')));
            $captchaId = htmlspecialchars(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('captcha_id')));

            if (!preg_match('/^[A-z0-9\._%+-]+@[A-z0-9\.-]+\.[A-z]{2,6}$/', $userEmail)){
                echo json_encode(array('done'=>false, 'msg'=>'email error'));
                return false;
            }

            if (!$this->validateCaptcha($captchaInput, $captchaId)) {
                $captchaId = RCMS_Tools_Tools::generateCaptcha();
                echo json_encode(array('done'=>false, 'msg'=>'captcha error', 'captchaId'=>$captchaId));
                return false;

            } else {
                $publish = $this->_session->moderatedReview?0:1;

                $review = new RCMS_Object_Product_ProductReview();
                $review->setProductId($productId);
                $review->setUserName($userName);
                $review->setUserEmail($userEmail);
                $review->setUserId(0);
                $review->setUserWebsite($userWebsite);
                $review->setDate(date("Y-m-d H:i:s"));
                $review->setContent($reviewContent);
                $review->setTopic($reviewTopic);
                $review->setPublish($publish);
                $review->setAbuse(0);
                $review->setRank(0);
                $review->setNotify(0);
                $newId = $review->save();

                if ($newId) {
                    if ($review->getPublish() || $isAdmin) {
                        $html  = '<li '.($isAdmin && !$review->getPublish()?'style="border: 1px dotted red;"':'').' class="hreview" id="review-'.$newId.'">';
                        $html .= $isAdmin ? '<p style="float: right;">
                            <a onclick="if(confirm(\'Are you sure want to delete this review?\')){deleteReview('.$newId.')}" class="deletereview" href="javascript:;">
                            <img src="'.$this->_websiteUrl.'system/images/ico_delete.gif" alt="Delete" />
                            </a>'.(!$review->getPublish()?'<a onclick="if(confirm(\'Are you sure to publish this review?\')){publishReview('.$newId.')}" class="publishreview" href="javascript:;">Publish</a>':'').'</p>' : '';
                        $html .= '<p class="summary">'.$review->getTopic().'</p>';
                        $html .= '<div class="description"><p>'.$review->getContent().'</p></div>';
                        $html .= '<p class="reviewer vcard">Reviewed by ';
                        $html .= '<a href="'.$review->getUserWebsite().'" class="url fn">'.$review->getUserName().'</a>';
                        $html .= '&nbsp;<abbr title="" class="dtreviewed">'.$review->getDate().'</abbr></p></li>';
                    }
                }

                $newCaptchaId = RCMS_Tools_Tools::generateCaptcha();
                echo json_encode(array('done'=>true,'html'=>$html,'prodid'=>$productId,'captchaId'=>$newCaptchaId));
                return true;
            }
        }
    }

    public function deletereviewAction(){
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') != '') {
			$id = $this->getRequest()->getParam('id');
			$review = new RCMS_Object_Product_ProductReview($id);
			if($review->delete()) {
				echo json_encode(array('done'=>true,'id'=>$id));
                return true;
			}
            echo json_encode(array('done'=>false,'msg'=>'Cannot delete review #'.$id));
            return false;
		}
        return false;
    }

    public function publishreviewAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost() && $this->getRequest()->getParam('id')!=''){
            $id = $this->getRequest()->getParam('id');
            $review = new RCMS_Object_Product_ProductReview($id);
            $review->setPublish(1);
            if ($review->save()){
                echo json_encode(array('done'=>true,'id'=>$id));
                return true;
            }
            echo json_encode(array('done'=>false,'msg'=>'Cannot publish review'));
            return false;
        }
        return false;
    }

    public function loadreviewsAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $userRole = isset($this->_session->currentUser)?unserialize($this->_session->currentUser)->getRoleId():0;
        $isAdmin = ($userRole == 3 || $userRole == 1 ? true : false);

        if ($this->getRequest()->isPost()){
            $productId  = $this->getRequest()->getParam('productId');
            $limit      = 10; //$this->getRequest()->getParam('limit')
            $offset     = $this->getRequest()->getParam('offset');

            $reviews = $this->_model->selectReviewByProductId($productId, $limit, $offset, $isAdmin);

            $result = array();

            foreach ($reviews as $review){

                if ($isAdmin || $review['publish'])
                {
                    $html  = '<li '. ($isAdmin && !$review['publish']?'style="border: 1px dotted red;"':'').' class="hreview" id="review-'.$review['id'].'">';
                    $html .= $isAdmin ? '<p style="float: right;">
                        <a onclick="if(confirm(\'Are you sure want to delete this review?\')){deleteReview('.$review['id'].')}" class="deletereview" href="javascript:;">
                        <img src="'.$this->_websiteUrl.'system/images/ico_delete.gif" alt="Delete" title="Delete"/></a>'.
                        (!$review['publish']?'<a onclick="if(confirm(\'Are you sure to publish this review?\')){publishReview('.$review['id'].')}" class="publishreview" href="javascript:;">Publish</a>':'').'</p>':'';
                    $html .= '<p class="summary">'.$review['topic'].'</p>';
                    $html .= '<div class="description"><p>'.$review['content'].'</p></div>';
                    $html .= '<p class="reviewer vcard">Reviewed by ';
                    $html .= '<a href="'.$review['user_website'].'" class="url fn">'.$review['user_name'].'</a>';
                    $html .= '&nbsp;<abbr title="" class="dtreviewed">'.$review['date'].'</abbr></p></li>';

                    array_push($result, $html);
                }
                $lastPortion = count($result)<$limit?true:false;
            }
            echo json_encode(array('done'=>true,'data'=>implode(' ',$result),'last'=>$lastPortion));
            return true;
        }
        return false;
    }


    public function voteforreviewAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()) {

            $value = $this->getRequest()->getParam('value');
            switch ($value){
                case 'yes':
                    $mark = 1;
                    break;
                case 'no':
                    $mark = -1;
                    break;
                default:
                    break;
            }
            $reviewId = $this->getRequest()->getParam('reviewId');

            if (isset($this->_session->votedReviews)){
                if (in_array($reviewId, $this->_session->votedReviews)){
                   echo json_encode(array('done'=>false,'msg'=>'voted'));
                   return false;
                }
            } else {
                $this->_session->votedReviews = array();
            }

            $review = new RCMS_Object_Product_ProductReview($reviewId);
            $newRank = $review->getRank() + $mark;
            $review->setRank($newRank);
            $review->save();

            array_push($this->_session->votedReviews, $reviewId);

            echo json_encode(array('done'=>true,'rank'=>$newRank));
            return true;
        }


    }

}
